#include "nc2db_Array2db.h"
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <vector>
#include <fstream>
#include "FortranFun.h"
using namespace std;
JNIEXPORT jint JNICALL Java_nc2db_Array2db_data2db
  (JNIEnv *env, jclass, jobjectArray array, jint year, jint type,jstring kind, jstring element)
  {
	 int  longitude; //经度0~360
     int  latitude; //纬度-90~90
	 int  layer;    //层  最大17，最小1
	 int  time;     //时间尺度，可以为日，月
	char ckind[32]={0};
    jboolean jb = true;
    char *tmp = (char*)(env->GetStringUTFChars(kind, &jb));
	strcpy(ckind, tmp);
	env->ReleaseStringUTFChars(kind,tmp);
	
	char celement[32]={0}; 
    jboolean jb2 = true;
    char *tmp2 = (char*)(env->GetStringUTFChars(element, &jb2));
	strcpy(celement, tmp2);
	env->ReleaseStringUTFChars(element,tmp2);
      
     jfloat *ctimerarray;    //
	 vector<float> dataf;    //用来动态的存储数据
     longitude = (env->GetArrayLength(array));
	 for(int i=0;i<longitude;i++)
    {
		jobjectArray  latarray = (jobjectArray)(env->GetObjectArrayElement(array, i));
		latitude = (env->GetArrayLength(latarray));
		for(int j =0;j< latitude;j++)
	    {
			jobjectArray  layerarray = (jobjectArray)(env->GetObjectArrayElement(latarray, j));
		    layer = (env->GetArrayLength(layerarray));
			for(int k=0;k< layer;k++)
		    {
                jfloatArray  timerarray = (jfloatArray)(env->GetObjectArrayElement(layerarray, k));
				time = (env->GetArrayLength(timerarray));
				ctimerarray = (env->GetFloatArrayElements(timerarray,NULL));
				jfloat* fArr = env->GetFloatArrayElements(timerarray,0);
				for(int m=0;m<time;m++)
			   {
				   // printf("%f \r\n", fArr[m]);
				    dataf.push_back(fArr[m]);
			   }
			   delete[] fArr;
			   env->ReleaseFloatArrayElements(timerarray,ctimerarray,0);
			}
		}
		// printf("%d \r\n", i);
	}
	 //int Iyear = year;
	// int Itype = type;
	 //int* pyear = &Iyear;
	// int* ptype = &Itype;
	 //int length = dataf.size(); 
	 //float * pdata = new float[dataf.size()];
	 float pdata[dataf.size()];
	 //int* plongitude = &longitude;
	 //int* platitude  = &latitude;
	 //int* player     = &layer;
	 //int* ptime      = &time;
	 int datalen     = dataf.size();
	 //int* pdatalen   = &datalen;
	  for(int i=0;i<dataf.size();i++)
		{
			  pdata[i] = dataf[i];
		}
	 printf("in the C++ \r\n");
	 //int state = write_to_db_(pdata,pdatalen,plongitude,platitude,player,ptime,pyear,ptype,ckind,celement);
	int state = write_to_db_(pdata,&datalen,&longitude,&latitude,&layer,&time,&year,&type,ckind,celement);
	//delete[] pdata;
 	jint res =time;
	 
	 return res;  
  }
  
  
  
  